LOCALSTORAGE


The localStorage object allows you to save key-value pairs in a web browser with no expiration date. This means the data stored persists even after the user closes the browser or restarts the computer.

What is localStorage?

localStorage is a part of the Web Storage API that provides a way to store data in the browser. Unlike cookies, the storage limit is much larger (around 5-10MB) and the data is not sent to the server with every HTTP request.

Basic Operations :

Storing Data

To store data in localStorage, use the setItem method:

localStorage.setItem('key', 'value');

Retrieving Data

To retrieve data from localStorage, use the getItem method:

const value = localStorage.getItem('key');

Removing Data

To remove a specific item from localStorage, use the removeItem method:

localStorage.removeItem('key');

Clearing All Data

To clear all data from localStorage, use the clear method:

localStorage.clear();

Storing Complex Data :

localStorage can only store strings. To store objects or arrays, you need to convert them to a string using JSON.stringify:

const user = { name: 'John', age: 30 };
    localStorage.setItem('user', JSON.stringify(user));

To retrieve and parse the data back into an object:

const user = JSON.parse(localStorage.getItem('user'));

Use Cases

Limitations

Best Practices

Resources for Further Learning